<?php
/**
 * Created by PhpStorm.
 * User: wcj
 * Date: 2017/2/13
 * Time: 11:35
 * 客房预订
 *说明  该系统中所有的支付  都在此控制器中
 */
class RoomAction extends CommAction{
    public function index(){
       //当前在线的房间库存
        $onlineRoom = M('room')->where(array('online'=>1))->order('sort')->select();
        foreach($onlineRoom as $k=>$val){
            $info[$k]['id'] = $val['id'];
            $info[$k]['name'] = $val['name'];
            $info[$k]['type'] = M('room_type')->where(array('id'=>$val['typeid']))->getField('name');
            $info[$k]['breakfast_price'] = M('order_room_breakfast')->where(array('id'=>$val['breakfastid']))->getField('price');
            $info[$k]['breakfast_type'] = M('order_room_breakfast')->where(array('id'=>$val['breakfastid']))->getField('type');
            $info[$k]['price'] = $val['price'];
            $info[$k]['hexiao_role'] = M('hexiao_role')->where(array('id'=>$val['hexiao_roleid']))->getField('name');
            if($val['logo'] == ''){
                $info[$k]['logo'] = '';
            }else{
                $programNname = explode('/',$_SERVER['REDIRECT_URL']);
                $info[$k]['logo'] = 'http://'.$_SERVER['HTTP_HOST'].'/'.$programNname[1].'/upload/room/'.$val['logo'];
            }
            $info[$k]['total_count'] = $val['total_count'];
            $info[$k]['num'] = $val['num'];
            $info[$k]['rest'] = $val['total_count'] - $val['num'];
            $info[$k]['create_time'] = date('Y-m-d H:i:s',$val['create_time']);
            $info[$k]['online'] = $val['online'];
            $info[$k]['sort'] = $val['sort'];
        }
        $this->assign('info',$info);
        //早餐(顺序依次为:不含早,含单早,含双早)
        $breakfastPrice = M('order_room_breakfast')->select();
        $this->assign('breakfastPrice',$breakfastPrice);
        $this->display();
    }

    //订房前检查是否还有空闲房间
    public function checkRestRoom(){
        if(IS_AJAX){
            $id = I('get.id');
            $info = M('room')->where(array('id'=>$id))->find();
            $rest = $info['total_count'] - $info['num'];
            if($rest > 0){
                //还有空余房间
                $this->ajaxReturn(array('val'=>0,'msg'=>'跳转'));
            }else{
                //无空余房间
                $this->ajaxReturn(array('val'=>1,'msg'=>'此房型已无剩余,看看其他的吧!'));
            }
        }
    }

    //正常订房支付页面
    public function prepareOrder(){
        $roomid = I('get.id');//房间id
        $pprice = I('get.pprice');//预定价格
        $this->assign('pprice',$pprice);
        //房间名+早餐类型
        $info = M('room')->where(array('id'=>$roomid))->find();
        $breakfastPrice = M('order_room_breakfast')->select();
        if($breakfastPrice[0]['price'] + $info['price'] == $pprice){
            $type = $breakfastPrice[0]['type'];
        }
        if($breakfastPrice[1]['price'] + $info['price'] == $pprice){
            $type = $breakfastPrice[1]['type'];
        }
        if($breakfastPrice[2]['price'] + $info['price'] == $pprice){
            $type = $breakfastPrice[2]['type'];
        }
        $this->assign('type',$type);
        $this->assign('info',$info);
        $starttime = I('get.starttime');//入店时间
        $endtime = I('get.endtime');//离店时间
        $this->assign('starttime',$starttime);
        $this->assign('endtime',$endtime);
        $openid = session::get('openid');
        $this->assign('openid',$openid);
        $this->display();
    }
  
    //正常订餐支付页面
    public function payFood(){
      $foodid = I('get.foodid');
      $openid = session::get('openid');
      $norms = I('get.norms');
      $num = I('get.num');
      $totalPrice = I('get.totalPrice');
      $lingqu_time = I('get.lingqu_time');
      $info = M('order_food_detail')->where(array('id'=>$foodid))->find();
      $this->assign('info',$info);
      $this->assign('norms',$norms);
      $this->assign('totalPrice',$totalPrice);
      $this->assign('lingqu_time',$lingqu_time);
      $this->assign('num',$num);
      $this->assign('openid',$openid);
      $this->display();
    }

    //我的订单中订餐支付页面
    public function payForMyFoodOrder(){
      $orderFoodid = I('get.orderFoodid');
      $this->assign('orderFoodid',$orderFoodid);
      $openid = session::get('openid');
      $this->assign('openid',$openid);
      $this->display();
    }
    //我的订单中订房支付页面
    public function payForMyRoomOrder(){
      $orderroomid = I('get.orderroomid');
      $this->assign('orderroomid',$orderroomid);
      $openid = session::get('openid');
      $this->assign('openid',$openid);
      $this->display();
    }
    //我的订单中所有订单支付页面
    public function payForMyAllOrder(){
      $orderAllid = I('get.orderAllid');
      $totalPrice = I('get.totalPrice');
      $this->assign('orderAllid',$orderAllid);
      $this->assign('totalPrice',$totalPrice);
      $this->display();
    }
    //立即购买  获取信息
    public function getMoney(){
     //订房日志
     if(IS_AJAX){
       $type = I('get.type');
          //正常下单订房
         if($type == 'orderRoom'){
             $map['userid'] = M('wxuser')->where(array('openid'=>session::get('openid')))->getField('id');
             $map['name'] = I('get.name');
             $map['mobile'] = I('get.mobile');
             $map['sex'] = I('get.sex');
             $map['room_id'] = I('get.roomid');//获取roomid
             $map['num'] = I('get.num');//房间数
             $map['price'] = I('get.totalPrice1');
             $map['yuding_time'] = time();
             $map['wx_orderid'] = '10012858'.time().rand(0,99999999);
             $map['starttime'] = strtotime(I('get.starttime'));
             $map['endtime'] = strtotime(I('get.endtime'));
             $map['yuding_days'] = ($map['endtime'] - $map['starttime'])/86400;
             $map['order_status'] = 0;
             $map['paytype'] = '订房';
             $map['beizhu'] = I('get.beizhu');
             //查询该用户是否有未支付的订单
             $ss['userid'] = $map['userid'];
             $ss['order_status'] = 0;//待支付
             $hasOrderNoPay = M('order_room_result')->where($ss)->find();
             if($hasOrderNoPay){
               $this->ajaxReturn(array('msg'=>'您有未完成的订单待支付,请先行支付!','val'=>1));
             }
             //判断此事是否还有空房间
             $info = M('room')->where(array('id'=>$map['room_id']))->find();
             $rest = $info['total_count'] - $info['num'];
             if($rest <= 0){
               $this->ajaxReturn(array('msg'=>'当前已无剩余房间了哦!','val'=>2));
             }
             //记录订房信息
             $orderRoom = M('order_room_result')->add($map);
             if($orderRoom){
              //支付环节
              $paySign = $this->getPaySign($map['price'],'orderRoom');
              $timestamp = strtolower($paySign['timeStamp']);
              $openid = session::get('openid');
              $this->ajaxReturn(array('msg'=>'订房成功,准备支付!','val'=>3,'paySign'=>$paySign,'timestamp'=>$timestamp,'money'=>$map['price'],'openid'=>$openid));
             }else{
              $this->ajaxReturn(array('msg'=>'信息录入出错!','val'=>4));
             }
         
       }
       // 正常下单支付餐品
       if($type == 'orderFood'){
           $map['userid'] = M('wxuser')->where(array('openid'=>session::get('openid')))->getField('id');
           $map['name'] = I('get.name');
           $map['mobile'] = I('get.mobile');
           $map['lingqu_time'] = I('get.lingqu_time');
           $map['sex'] = I('get.sex');
           $map['foodid'] = I('get.foodid');//获取foodid
           $map['kindid'] = I('get.kindid');
           $map['num'] = I('get.num');//数量
           $map['price'] = I('get.price');
           $map['norms'] = I('get.norms');
           $map['order_time'] = time();
           $map['yuding_time'] = time();
           $map['wx_orderid'] = '10012858'.time().rand(0,99999999);
           $map['order_status'] = 0;
           $map['paytype'] = '订餐';
           $map['beizhu'] = I('get.beizhu');
           //查询该用户是否有未支付的订单
           $ss['userid'] = $map['userid'];
           $ss['order_status'] = 0;//待支付
           $hasOrderNoPay = M('order_food_record')->where($ss)->find();
           if($hasOrderNoPay){
             $this->ajaxReturn(array('msg'=>'您有未完成的订单待支付,请先行支付!','val'=>1));
           }
           //查询套餐是否还有剩余
           $info = M('order_food_detail')->where(array('id'=>$map['foodid']))->find();
           if($info['rest'] <= 0){
             $this->ajaxReturn(array('msg'=>'当前已无剩余套餐了哦!','val'=>2));
           }
           //记录订房信息
           $orderFood = M('order_food_record')->add($map);
           if($orderFood){
            //更新已订房信息
            // $dd['rest'] = $info['rest'] - $map['num'];
            // M('order_food_detail')->where(array('id'=>$map['foodid']))->save($dd);
            //支付环节
            $paySign = $this->getPaySign($map['price'],'orderFood');
            $timestamp = strtolower($paySign['timeStamp']);
            $openid = session::get('openid');
            $this->ajaxReturn(array('msg'=>'订餐成功,准备支付!','val'=>3,'paySign'=>$paySign,'timestamp'=>$timestamp,'money'=>$map['price'],'openid'=>$openid));
           }else{
            $this->ajaxReturn(array('msg'=>'信息录入出错!','val'=>4));
           }
       }
       //通过我的订单支付订餐
       if($type == 'orderFoodByMy'){
           $map['userid'] = M('wxuser')->where(array('openid'=>session::get('openid')))->getField('id');
           $map['id'] = I('get.orderFoodid');
           $myOrderFoodInfo = M('order_food_record')->where(array('id'=>$map['id']))->find();
           //查询套餐是否还有剩余
           $info = M('order_food_detail')->where(array('id'=>$myOrderFoodInfo['foodid']))->find();
           if($info['rest'] <= 0){
             $this->ajaxReturn(array('msg'=>'当前已无剩余套餐了哦!','val'=>2));
           }
            //支付环节
            $paySign = $this->getPaySign($myOrderFoodInfo['price'],'orderFoodByMy');
            $timestamp = strtolower($paySign['timeStamp']);
            $openid = session::get('openid');
            $this->ajaxReturn(array('msg'=>'订餐成功,准备支付!','val'=>3,'paySign'=>$paySign,'timestamp'=>$timestamp,'money'=>$map['price'],'openid'=>$openid));
       }
       //通过我的订单支付订房
       if($type == 'orderRoomByMy'){
           $map['userid'] = M('wxuser')->where(array('openid'=>session::get('openid')))->getField('id');
           $map['id'] = I('get.orderroomid');
           $myOrderRoomInfo = M('order_room_result')->where(array('id'=>$map['id']))->find();
           //查询房间是否还有剩余
           $info = M('room')->where(array('id'=>$myOrderRoomInfo['room_id']))->find();
           $rest = $info['total_count'] - $info['num'];
           if($rest <= 0){
             $this->ajaxReturn(array('msg'=>'当前已无剩余客房了哦!','val'=>2));
           }
            //支付环节
            $paySign = $this->getPaySign($myOrderRoomInfo['price'],'orderRoomByMy');
            $timestamp = strtolower($paySign['timeStamp']);
            $openid = session::get('openid');
            $this->ajaxReturn(array('msg'=>'订餐成功,准备支付!','val'=>3,'paySign'=>$paySign,'timestamp'=>$timestamp,'money'=>$map['price'],'openid'=>$openid));
       }
       //通过我的订单支付全部订单待续
       
     }
    }
    //支付
    public function getPaySign($money=1,$type='orderRoom'){
        Vendor('Jsapipay.example.WxPaye');
        Vendor('Jsapipay.lib.WxPayl');
        Vendor('Jsapipay.lib.Config');
        Vendor('Jsapipay.lib.Data');
        Vendor('Jsapipay.lib.Exception');
        $actId = 604;
        define('APPID', "wx9d6ce34d0ab6bd64");
        define('MCHID', "10012858");
        define('KEY', "weickdfl13098djcnhw3764hd87tc64w");
        define('APPSECRET', "a87cb43b41d3812ed197a920c1566e06");
        //获取活动名称，作为微信支付凭证的商品详情,优先使用set中的body
        $openId = session::get('openid');
        if($type == 'orderRoom'){
          $actName = "酒店订房支付";
        }
        if($type == 'orderFood'){
          $actName = "酒店订餐支付";
        }
        if($type == 'orderFoodByMy'){
          $actName = "酒店订房支付";
        }
        if($type == 'orderRoomByMy'){
          $actName = "酒店订餐支付";
        }
        $tools = new JsApiPay();

        $input = new WxPayUnifiedOrder();
        $input->SetBody($actName);//设置商品或支付单简要描述
        $amount = $money*100;//测试
        $input->SetAttach($money);//设置附加数据
        $input->SetOut_trade_no(MCHID . date("His").rand(0000,9999));//设置商户系统内部的订单号,32个字符内
        $input->SetTotal_fee($amount);//设置订单总金额，只能为整数
        $input->SetTime_start(date("YmdHis"));//设置订单生成时间，格式为yyyyMMddHHmmss
        $input->SetTime_expire(date("YmdHis", time() + 600));//设置订单失效时间
        $input->SetGoods_tag("test");//设置商品标记
        $input->SetNotify_url("http://game.guangjixinxi.com/JinLingHotel/Crm/Update/room");//设置接收微信支付异步通知回调地址
        $input->SetTrade_type("JSAPI");//设置取值如下：JSAPI，NATIVE，APP
        $input->SetOpenid($openId);//设置trade_type=JSAPI的时候，此参数必传
        $order = WxPayApi::unifiedOrder($input, 6, APPID, MCHID, KEY);//统一下单
        $jsApiParameters = $tools->GetJsApiParameters($order, KEY);
        // dump(json_decode($jsApiParameters, true));
        return json_decode($jsApiParameters, true);
    }
    //更改订房支付状态
    public function changeRoomStatus(){
      if(IS_AJAX){
        $openid = I('get.openid');
        $num = I('get.num');
        $userid = M('wxuser')->where(array('openid'=>$openid))->getField('id');
        //获取该用户订房记录中未支付订单的id
        $notPay['userid'] = $userid;
        $notPay['order_status'] = 0;
        $orderRoomNotPayRoomid = M('order_room_result')->where($notPay)->getField('room_id');
        //更新支付状态
        $map['order_status'] = 1;//已支付
        $map['order_time'] = time();
        $where['userid'] = $userid;
        $where['order_status'] = 0;
        $save = M('order_room_result')->where($where)->save($map);//更新为已支付
        //更新房间数
        $info = M('room')->where(array('id'=>$orderRoomNotPayRoomid))->find();
        $dd['num'] = $info['num'] + $num;
        M('room')->where(array('id'=>$orderRoomNotPayRoomid))->save($dd);
        // if($save){
            $this->ajaxReturn(array('val'=>1,'msg'=>'支付成功'));//成功
        // }
        
      }
    }

    //更改订餐支付状态
    public function changeFoodStatus(){
      if(IS_AJAX){
        $openid = I('get.openid');
        $num = I('get.num');
        $userid = M('wxuser')->where(array('openid'=>$openid))->getField('id');
        //获取该用户订房记录中未支付订单的id
        $notPay['userid'] = $userid;
        $notPay['order_status'] = 0;
        $orderFoodNotPayFoodid = M('order_food_record')->where($notPay)->getField('foodid');
        //更新支付状态
        $map['order_status'] = 1;//已支付
        $map['pay_time'] = time();
        $where['userid'] = $userid;
        $where['order_status'] = 0;
        $save = M('order_food_record')->where($where)->save($map);//更新为已支付
        //更新餐品数
        $info = M('order_food_detail')->where(array('id'=>$orderFoodNotPayFoodid))->find();
        $dd['rest'] = $info['rest'] - $num;
        M('order_food_detail')->where(array('id'=>$orderFoodNotPayFoodid))->save($dd);
        if($save){
            $this->ajaxReturn(array('val'=>1,'msg'=>'支付成功'));//成功
        }
        
      }
    }

    //更改订房订单中的支付状态
    public function changeRoomOrderStatus(){
      if(IS_AJAX){
        $openid = I('get.openid');
        $userid = M('wxuser')->where(array('openid'=>$openid))->getField('id');

        $map['order_status'] = 1;//已支付
        $map['order_time'] = time();
        $where['userid'] = $userid;
        $where['order_status'] = 0;
        $notPayRoomid = M('order_room_result')->where($where)->getField('room_id');
        $num = M('order_room_result')->where($where)->getField('num');
        $save = M('order_room_result')->where($where)->save($map);//更新为已支付
        //更新房间数
        $info = M('room')->where(array('id'=>$notPayRoomid))->find();
        $dd['num'] = $info['num'] + $num;
        M('room')->where(array('id'=>$notPayRoomid))->save($dd);
        if($save){
            $this->ajaxReturn(array('val'=>1,'msg'=>'支付成功'));//成功
        }
        
      }
    }

    //更改订餐订单中订房支付状态
    public function changeFoodOrderStatus(){
      if(IS_AJAX){
        $openid = I('get.openid');
        $userid = M('wxuser')->where(array('openid'=>$openid))->getField('id');
        $map['order_status'] = 1;//已支付
        $map['pay_time'] = time();
        $where['userid'] = $userid;
        $where['order_status'] = 0;
        $notPayFoodid = M('order_food_record')->where($where)->getField('foodid');
        $num = M('order_food_record')->where($where)->getField('num');
        $save = M('order_food_record')->where($where)->save($map);//更新为已支付
        //更新餐品数
        $info = M('order_food_detail')->where(array('id'=>$notPayFoodid))->find();
        $dd['rest'] = $info['rest'] - $num;
        M('order_food_detail')->where(array('id'=>$notPayFoodid))->save($dd);
        if($save){
            $this->ajaxReturn(array('val'=>1,'msg'=>'支付成功'));//成功
        }
        
      }
    }
}